<?php

namespace App\Console;

use App\Libs\Util;
use App\Libs\WeChat\Transfer\WxTransfer;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        //
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        //1.正常拼团   activity_num 3 成团数限制 0  true   队伍人数为3正常成团 时间结束之后如果有2个人的也算成功
        //2.设置成团数 如果成团数达到了自动结束
        //如果设置了成团数，则不可以重复购买


        $schedule->call(function () {
            try {
                ini_set('memory_limit', '-1');
                echo memory_get_usage();
                $activity = DB::table('activity')->where(['is_valid'=>1])->get();
                if($activity){
                    foreach ($activity as $values){
                        //如果过期了 直接没成功的退款
                        if(strtotime($values->end_time) <= time() ){
                            $activity_goods = DB::table('activity_goods')->leftjoin('activity_team','activity_goods.sku','=','activity_team.sku')->where(['activity_id'=>$values->ac_id])->get(['goods_id','activity_goods.sku']);
                            //var_dump($activity_goods);exit;
                            foreach ($activity_goods as $v){
                                //查询队伍
                                $activity_team = DB::table('activity_team')->where(['activity_goods_id'=>$v->goods_id,'sku'=>$v->sku,'ac_id'=>$values->ac_id])->get();
                                foreach ($activity_team as $value){
                                    //查询队伍人数是否足够 不够的话 查询订单退款
                                    $activity_users = DB::table('activity_users')->where(['at_id'=>$value->at_id,'activity_goods_id'=>$v->goods_id,'sku'=>$v->sku])->get();
                                    $nums = count($activity_users);
                                    if($values->team_num){
                                        $judge_num = $values->activity_num;
                                    }else{
                                        $judge_num = $values->activity_num-1;
                                    }
                                    if($nums >= ($judge_num)){
                                        continue;
                                    }else{
                                        //查询订单信息并退款
                                        foreach ($activity_users as $item){
                                            $str = $item->user_id.'_'.$v->goods_id.'_'.$v->sku.'_'.$value->at_id.'_'.$values->ac_id;
                                            $orders = DB::table('ibrand_order')->where(['user_id'=>$item->user_id,'channel'=>$str])->first();
                                            //var_dump($orders);
                                            if($orders){
                                                //如果状态不对 记录
                                                if($orders->status!=2){
                                                    savelog('refund_pintuan', (json_encode($orders)));
                                                    continue;
                                                }
                                                $wx = new WxTransfer();
                                                $refund = [];
                                                $refund['order_no']=$orders->order_no;
                                                $refund['total_fee']=$orders->total;
                                                $res = $wx->refund($refund);
                                                if($res){
                                                    //修改订单的状态
                                                    DB::table('ibrand_order')->where(['order_no'=>$orders->order_no])->update(['status'=>7]);
                                                    $user = DB::table('ibrand_user')->where(['id'=>$orders->user_id])->first();
                                                    $openid = $user->openid;
                                                    //退还积分
                                                    $member_info = get_member($openid);
                                                    if($member_info){
                                                        $before_bonus = $member_info->bonus;
                                                        $change_bonus = ceil($orders->total/100);
                                                        $after_bonus = $before_bonus-$change_bonus;
                                                        $status = 1;
                                                        $type = 2;
                                                        //调用微信的接口加积分
                                                        $record_bonus = sprintf("退还%s元，扣除%u积分", $change_bonus, $change_bonus);
                                                        $result = Util::updateMember($member_info->code,$record_bonus,-$change_bonus);
                                                        if($result['errcode']==0){
                                                            add_bonus_record($openid,$before_bonus,$change_bonus,$after_bonus,$status,$type,1,'');
                                                        }else{
                                                            savelog('wx_bonus', '订单已经支付过'.$orders->order_no.'错误：'.$result['errmsg']);
                                                        }
                                                    }

                                                    echo '退款成功';
                                                    savelog('refund_pintuan_success', (json_encode($orders)));
                                                }else{
                                                    savelog('refund_pintuan_fail', (json_encode($orders)));
                                                }
                                            }else{
                                                savelog('refund_pintuan_fail', (json_encode($str)));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else{
                            //判断队伍人数是否足够 如果足够判断每个队伍的人数 如果每个队伍人数都满的话 则算成功 否则不成功不做操作
                            //$activity_team = DB::table('activity_team')->where(['ac_id'=>$values->ac_id])->get();
                            if($values->team_num){
                                $res = DB::select("SELECT activity_users.ac_id,COUNT(*) AS ac_num FROM `activity_team` LEFT JOIN activity_users ON activity_users.at_id = activity_team.at_id WHERE activity_team.ac_id = ? GROUP BY activity_users.at_id HAVING ac_num >= ?",[$values->ac_id,$values->activity_num]);
                                $team_num = count($res);
                                //说明团数和人数都已经足够了
                                if($team_num >= $values->team_num){
                                    //结束活动之后要把没有成团的队伍退款
                                    $activity_team = DB::table('activity_team')->where(['ac_id'=>$values->ac_id])->get();
                                    if(!$activity_team){
                                        continue;
                                    }
                                    foreach ($activity_team as $value){
                                        //查询队伍人数是否足够 不够的话 查询订单退款
                                        $activity_users = DB::table('activity_users')->where(['at_id'=>$value->at_id])->get();
                                        $nums = count($activity_users);
                                        //如果小于
                                        if($nums < ($values->activity_num)){
                                            //查询订单信息并退款
                                            foreach ($activity_users as $item){
                                                $str = $item->user_id.'_'.$item->activity_goods_id.'_'.$item->sku.'_'.$value->at_id.'_'.$values->ac_id;
                                                $orders = DB::table('ibrand_order')->where(['user_id'=>$item->user_id,'channel'=>$str])->first();
                                                //var_dump($orders);
                                                if($orders){
                                                    //如果状态不对 记录
                                                    if($orders->status!=2){
                                                        savelog('refund_pintuan', (json_encode($orders)));
                                                        continue;
                                                    }
                                                    $wx = new WxTransfer();
                                                    $refund = [];
                                                    $refund['order_no']=$orders->order_no;
                                                    $refund['total_fee']=$orders->total;
                                                    $res = $wx->refund($refund);
                                                    if($res){
                                                        //修改订单的状态
                                                        DB::table('ibrand_order')->where(['order_no'=>$orders->order_no])->update(['status'=>7]);
                                                        $user = DB::table('ibrand_user')->where(['id'=>$orders->user_id])->first();
                                                        $openid = $user->openid;
                                                        //退还积分
                                                        $member_info = get_member($openid);
                                                        if($member_info){
                                                            $before_bonus = $member_info->bonus;
                                                            $change_bonus = ceil($orders->total/100);
                                                            $after_bonus = $before_bonus-$change_bonus;
                                                            $status = 1;
                                                            $type = 2;
                                                            //调用微信的接口加积分
                                                            $record_bonus = sprintf("退还%s元，扣除%u积分", $change_bonus, $change_bonus);
                                                            $result = Util::updateMember($member_info->code,$record_bonus,-$change_bonus);
                                                            if($result['errcode']==0){
                                                                add_bonus_record($openid,$before_bonus,$change_bonus,$after_bonus,$status,$type,1,'');
                                                            }else{
                                                                savelog('wx_bonus', '订单已经支付过'.$orders->order_number.'错误：'.$result->errmsg);
                                                            }
                                                        }

                                                        echo '退款成功';
                                                        savelog('refund_pintuan_success', (json_encode($orders)));
                                                    }else{
                                                        savelog('refund_pintuan_fail', (json_encode($orders)));
                                                    }
                                                }else{
                                                    savelog('refund_pintuan_fail', (json_encode($str)));
                                                }
                                            }
                                        }

                                    }
                                    //说明团队已经足够了 可以结束了活动了
                                    DB::table('activity')->where(['ac_id'=>$values->ac_id])->update(['is_valid'=>0]);
                                    savelog('pintuan_succeed', (json_encode($values)));
                                }
                            }
                        }
                    }
                }
                echo '<br/>';
                echo memory_get_usage();
                echo '暂无需要退款活动';
            } catch (\Exception $ex) {
                var_dump($ex->getMessage() . $ex->getLine());
                savelog('export_ald_log', $ex->getMessage() . $ex->getLine());
            }
        })->cron('*/1 * * * *');



        $schedule->call(function () {
            /*ini_set('memory_limit', '-1');
            try {
                sleep(10);
                $activity = DB::table('activity')->where(['is_valid'=>1])->get();
                //如果活动时间结束了 自动改为失效状态
                if($activity){
                    foreach($activity as $v){
                        $data = '';
                        var_dump(time() >= (strtotime($v->end_time)-3600));
                        if(time() >= (strtotime($v->end_time)-3600)){
                            $template_id = 'JD_4etEMOuMy0eTv7Ds-t1w3Hqibv4rgi_rbH5eExAQ';
                            $data = array(
                                'keyword1'=>array('value'=>'暴抱团','color'=>'#7167ce'),
                                'keyword2'=>array('value'=>'您参与的暴抱团即将超时失败啦！','color'=>'#7167ce'),
                                'keyword3'=>array('value'=>'还剩1小时！','color'=>'#7167ce'),
                            );
                            $key = 'push_activity_no_end_'.$v->ac_id;
                        }
                        var_dump(time() >= strtotime($v->end_time));
                        if(time() >= strtotime($v->end_time)){
                            DB::table('activity')->where(['ac_id'=>$v->ac_id])->update(['is_valid'=>0]);
                            $template_id = 'g7Ni9Hii3rgzx3a3z-3jJtZeMaaFUvqesDurZEYFR_w';
                            $data = array(
                                'keyword1'=>array('value'=>'暴抱团','color'=>'#7167ce'),
                                'keyword2'=>array('value'=>'截止到4月30日21点暴抱团即将结束，快看看还有啥！','color'=>'#7167ce'),
                            );
                            $key = 'push_activity_end_'.$v->ac_id;
                            //查询参与活动的人推送消息
                        }
                        var_dump($data);
                        if($data){
                            $activity_team = DB::table('activity_users')->leftjoin('ibrand_user','activity_users.user_id','=','ibrand_user.id')->where(['ac_id'=>$v->ac_id])->get(['ibrand_user.openid']);
                            foreach ($activity_team as $value){
                                //Redis::del($key);
                                $res = Redis::sismember($key, $value->openid);
                                var_dump($res);
                                if(!$res){
                                    sendTemplate($value->openid,$data,$template_id);
                                    Redis::sadd($key, $value->openid);
                                    echo '成功';
                                }
                            }
                            Redis::expire($key,99);
                        }
                    }
                }else{
                    echo '暂无需要修改的活动';
                }
            } catch (\Exception $ex) {
                var_dump($ex->getMessage() . $ex->getLine());
                savelog('export_ald_log', $ex->getMessage() . $ex->getLine());
            }*/
        })->cron('*/1 * * * *');
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}
